package com.xxx.system.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxx.base.exception.BusinessException;
import com.xxx.system.domain.Logininfo;
import com.xxx.system.domain.Menu;
import com.xxx.system.dto.LoginDTO;
import com.xxx.system.jwt.JwtUtil;
import com.xxx.system.jwt.Payload;
import com.xxx.system.mapper.LogininfoMapper;
import com.xxx.system.mapper.MenuMapper;
import com.xxx.system.mapper.PermissionMapper;
import com.xxx.system.query.LogininfoQuery;
import com.xxx.system.service.ILogininfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类: 登录信息Logininfo
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LogininfoServiceImpl implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Logininfo> findAll() {
        return logininfoMapper.findAll();
    }

    @Override
    public Logininfo findOne(Long id) {
        return logininfoMapper.findOne(id);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        //删除角色
        logininfoMapper.delete(id);
    }

    @Override
    @Transactional
    public void add(Logininfo logininfo) {
        //添加角色信息
        logininfoMapper.add(logininfo); //自增id
    }

    @Override
    @Transactional
    public void update(Logininfo logininfo) {
        logininfoMapper.update(logininfo);
    }

    @Override
    public void patchDelete(Long[] ids) {
        logininfoMapper.patchDelete(ids);
    }

    @Override
    public PageInfo<Logininfo> queryPage(LogininfoQuery logininfoQuery) {
        //1.开启分页
        PageHelper.startPage(logininfoQuery.getCurrentPage(), logininfoQuery.getPageSize());
        //a.查询总数量 - count()
        //b.会根据方言 mysql 自动实现分页查询,如果是mysql就会使用limit查询
        //c.自动计算limit的第一个参数: (currentPage-1)*pageSize
        //2.操作数据库
        List<Logininfo> data = logininfoMapper.queryPage(logininfoQuery);
        return new PageInfo<>(data);
    }

    @Override
    public String login(LoginDTO loginDTO) {
        //校验参数类型
        if (StrUtil.isBlank(loginDTO.getAccount())
                || StrUtil.isBlank(loginDTO.getPassword())
                || loginDTO.getType() == null
        ) {
            throw new BusinessException("参数不能为空");
        }
        //根据usernaeme和type查询tb_longinfor
        Logininfo logininfo = logininfoMapper.findByUesrnameAndType(loginDTO);
        if (logininfo == null) {
            throw new BusinessException("账号不存在");
        }
        //前端穿的数据也需要进行加密
        String passwordFromUser = SecureUtil.md5(loginDTO.getPassword() + logininfo.getSalt());
        //对比密码
        if (!passwordFromUser.equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误");
        }
        //获取密码过后查询该用户用用的权限信息
        List<String> perms = permissionMapper.findPermsByLogininInfoId(logininfo.getId());

        //获取密码过后查询该用户用用的菜单信息
        List<Menu> menus = menuMapper.findMenusByLogininInfoId(logininfo.getId());
        List<Menu> menuTree = getMenuTree(menus);
        //密码正确,生成jwt字符串,封装成token请求
        Payload payload = new Payload();
        payload.setPermissions(perms);
        payload.setMenus(menuTree);
        //信息脱敏
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        payload.setLogininfo(logininfo);
        String jwtToken = JwtUtil.generateToken(payload);
        return jwtToken;
    }

    private List<Menu> getMenuTree(List<Menu> menuList){
        //类型树集合
        List<Menu> typeTree = new ArrayList<>();

        Map<Long, Menu> map = new HashMap<>();//封装进map集合
        //进行遍历,先把所有的数据放进map集合中
        for (Menu menu : menuList) {
            map.put(menu.getId(), menu);
        }
        //进行遍历判断是否是父类型还是子类型
        for (Menu menu : menuList) {
            Long parentId = menu.getParentId();
            if (parentId == null) {
                typeTree.add(menu);//所有的父类型
            } else {
                Menu parent = map.get(parentId);
                //加强判断,防止父类型为空
                if (parent != null) {
                    //在else里面肯定为子类型,把子类型放入子类型集合中
                    parent.getChildren().add(menu);
                }
            }
        }
        return typeTree;
    }
}
